<?php

namespace SinoPHP\BbdBoss\Model;

use SinoPHP\BbdBoss\Defines\StaticConfig;
use Upfor\UpforPHP\Model;

class ServerIp extends Model {

    const vip = 1;
    const rip = 2;
    const single = 3;
    /**
     * 当前登录的管理员用户信息(来自SESSION)
     *
     * @var array|null
     */
    private $userInfo;

    public function __construct() {
        parent::__construct();
        $this->userInfo = getCurrentAdminUserInfo();
    }

    /**
     * 检查字段是否已经存在
     *
     * @param string $field
     * @param string $value
     * @param int    $id
     * @return array|mixed
     */
    public function checkIsExistence($field = '', $value = '', $id = null) {
        if ($id) {
            $sql = "SELECT $field FROM `server_ip` WHERE `$field` = '$value' AND `ip_id` != $id LIMIT 1";

            return $this->db->query($sql);
        }

        return $this->getRow($field, ["$field" => $value]);
    }

    /**
     * 获取IP列表
     *
     * @param string $fields
     * @param string $condition
     * @param string $query
     * @param null   $limit
     * @param null   $offset
     * @return array
     */
    public function getIpList($fields = '', $condition = '', $query = '', $limit = null, $offset = null) {
        $sql = "SELECT {$fields} 
                FROM `server_ip`
                LEFT JOIN admin_user ON server_ip.operator_id = admin_user.admin_user_id
                WHERE " . $condition;
        //模糊搜索
        if ($query || is_numeric($query)) {
            $sql .= " AND (server_ip.ip LIKE '%" . trim($query) . "%' OR server_ip.hostname LIKE '%" . trim($query) . "%' OR server_ip.server_area LIKE '%" . trim($query) . "%' OR admin_user.real_name LIKE '%" . trim($query) . "%' )";
        }

        $sql .= " ORDER BY server_ip.hostname,server_ip.ip_id DESC ";
        if ($limit) {
            $sql .= "LIMIT {$offset},{$limit}";
        }

        $data = $this->db->query($sql);

        return $data;

        //构建sql
        $sql = "SELECT 
                  {$fields} 
                FROM 
                  `server_ip`
                LEFT JOIN server_group_ip ON server_group_ip.ip_id = server_ip.ip_id
                LEFT JOIN server_group ON server_group_ip.server_group_id = server_group.server_group_id
                LEFT JOIN admin_user ON server_ip.operator_id = admin_user.admin_user_id
                WHERE " . $condition;

        //模糊搜索
        if ($query || is_numeric($query)) {
            $sql .= " AND (server_ip.ip LIKE '%" . trim($query) . "%' OR server_ip.hostname LIKE '%" . trim($query) . "%' OR server_ip.server_area LIKE '%" . trim($query) . "%' OR admin_user.real_name LIKE '%" . trim($query) . "%' )";
        }

        $sql .= " AND server_ip.is_delete = 0 ORDER BY server_ip.hostname,server_ip.ip_id DESC ";
        if ($limit) {
            $sql .= "LIMIT {$offset},{$limit}";
        }
        //组合完整sql 进行查询
        $data = $this->db->query($sql);

        return $data;
    }

    /**
     * 查询所有服务器组，返回一位数组
     *
     * @return array
     */
    public function getServerGroupList() {
        $data = array();
        $this->setTableName('server_group');
        $res = $this->getList('server_group_id,server_name', ['status' => 1]);
        if (!$res) {
            return $data;
        }
        foreach ($res as $value) {
            $data[$value['server_group_id']] = $value['server_name'];
        }

        return $data;
    }

    /**
     * 获取ip日志
     *
     * @param int $id
     * @param int $pageSize
     * @return array
     */
    public function getIpLogById($id, $pageSize) {
        $sql = "SELECT 
                  `server_ip_log`.`create_time`,`operate_type`,`real_name`,`detail`
                FROM 
                  `server_ip_log`
                LEFT JOIN admin_user ON server_ip_log.admin_user_id = admin_user.admin_user_id
                WHERE `ip_id`={$id} ORDER By `log_id` DESC  LIMIT {$pageSize} ";

        return $this->db->query($sql);
    }

    /**
     * 根据id获取日志
     *
     * @param array $ids
     * @param int   $size
     * @return array
     */
    public function getIpLogList($ids, $size) {
        $data = [];
        $fields = 'real_name,S.create_time,operate_type,detail';
        foreach ($ids as $id) {
            $this->db()->table('server_ip_log', 'S');
            $this->db()->field($fields);
            $this->db()->join(['admin_user', 'U'], ['S.admin_user_id' => 'U.admin_user_id']);
            $this->db()->where(['ip_id' => $id]);
            $this->db()->order('S.create_time', 'DESC');
            $this->db()->limit($size);
            $data[$id] = $this->db()->getList();
        }

        return $data;
    }

    /**
     * 批量修改IP类型 计录日志
     *
     * @param $ids
     * @param $newIpType
     */
    public function insertBatchSetIpTypeLog($ids, $newIpType) {
        $ipTypeList = StaticConfig::$ipType;
        $sql = "INSERT INTO `server_ip_log` (`ip_id`,`admin_user_id`,`create_time`,`operate_type`,`detail`) VALUES ";
        foreach ($ids as $id => $ipType) {
            $sql .= "({$id},";
            $sql .= "{$this->userInfo['admin_user_id']},";
            $sql .= time() . ",";
            $sql .= "'设置ip类型',";
            $sql .= "'原ip类型为：{$ipTypeList[$ipType]} 修改为：{$ipTypeList[$newIpType]}'),";
        }

        $this->db->query(substr($sql, 0, -1));
    }

    /**
     * 批量暂停/启用 计录日志
     *
     * @param $data
     * @param $idList
     */
    public function insertPauseIpLog($data, $idList) {
        $sql = "INSERT INTO `server_ip_log` (`ip_id`,`admin_user_id`,`create_time`,`operate_type`,`detail`) VALUES ";
        foreach ($idList as $id) {
            $sql .= "({$id},";
            $sql .= "{$data['admin_user_id']},";
            $sql .= $data['create_time'] . ",";
            $sql .= "'$data[operate_type]',";
            $sql .= "'$data[detail]'),";
        }

        $this->db->query(substr($sql, 0, -1));
    }

    /**
     * 获取IP详情
     *
     * @param  array $where
     * @return array
     */
    public function getIpInfo($where = array()) {
        $cols = [
            'ip_id',
            'ip',
            'dnspod_id',
            'monitor_id',
            'status',
            'ip_domain_id',
            'monitor_status',
        ];

        return $this->getRow($cols, $where);
    }

    /**
     * 获取简单IP列表
     *
     * @param  array $where
     * @param  array $orderBy
     * @return array
     */
    public function getIpListSimple($where, $orderBy = null) {
        $cols = [
            'ip_id',
            'ip',
            'server_area',
            'dnspod_id',
            'monitor_id',
            'status',
            'ip_domain_id',
            'monitor_status',
        ];

        return $this->getList($cols, $where, $orderBy);
    }

    /**
     * 检查ip是否被虚拟节点绑定过
     *
     * @param $id   ip的id
     * @return boolean
     */
    public function checkIsBindByVirtualNode($id) {
        //取出被虚拟节点绑定的所有ip
        $this->db()->table('virtual_node');
        $this->db()->field('real_ip_ids,server_ip_id');
        $this->db()->where(['is_delete' => 0]);
        $res = $this->db()->getList();
        if (!$res) {
            return false;
        }
        $ipString = '';
        foreach ($res as $item) {
            $ipString .= $item['server_ip_id'] . ',' . $item['real_ip_ids'] . ',';
        }
        if (is_array($id)) {
            $ipArray = explode(',', $ipString);
            $ipArray = array_unique($ipArray);
            $insectArray = array_intersect($ipArray, $id);
            if ($insectArray) {
                return $insectArray;
            }

            return false;
        }
        if (strpos($ipString, $id) !== false) {
            return true;
        }

        return false;
    }
}
